package com.itheima.exception;

import com.itheima.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理唯一约束的异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e){
        //Duplicate entry 'admin' for key 'idx_username'4
        e.printStackTrace();

        //1. 获取信息
        String msg = e.getMessage();

        //2. 判定是否是唯一约束的异常
        if(msg.contains("Duplicate entry")){

            //3. 取得用户名
            String name = msg.split(" ")[2];

            return R.error(name + " , 已存在！");
        }

        return R.error("未知错误！");

    }


    /**
     * 处理自定义的异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R handleCustomException(CustomException e){
        e.printStackTrace();
        return R.error(e.getMessage());
    }
}
